﻿@{
    ViewBag.Title = "รายละเอียดรายการจ่าย [DP]";

    int intReqId = (int?) ViewBag.RequestId ?? 0;
    int intDispenseId = (int?)ViewBag.DispenseId ?? 0;
    int intProjectId = (int?)ViewBag.ProjectId ?? 0;

    var db = new GERPContext();
    var serviceRequest = new KPIS.GERP.WEB.GIMS.RequestParcelService.RequestParcelServiceClient();
    string status = ViewBag.RequestStatus;
    string result = serviceRequest.GetStatusName(status);
    ViewBag.StatusName = result;
    var history = db.DispenseHistorys.ToList();

    var serviceReq = new KPIS.GERP.WEB.GIMS.RequestParcelService.RequestParcelServiceClient();
    int intReqBy = Convert.ToInt32(ViewBag.RequestBy);
    string strFullName = intReqBy != 0 ? serviceReq.GetNameRequestBy(intReqBy) : "";
    ViewBag.FullName = strFullName;

    var mfp = new RequestParcel {ReqParcelId = intReqId};
    var rp = serviceReq.SelectRequestParcel(mfp, null).FirstOrDefault();
    string strRecordStatus = rp.RecordStatus;
    
    IEnumerable<IGrouping<int?, RequestParcelDtl>> modelRequest;
    var serviceDisp = new KPIS.GERP.WEB.GIMS.DispenseService.DispenseServiceClient();
    if (strRecordStatus == "A")
    {
        var mfr = new RequestParcelDtl {ReqId = intReqId, RecordStatus = "!D"};
        var incr = new[] {"RequestParcel", "RequestParcel.WarehousePermit"};
        var parcelDtl = serviceDisp.SelectRequestParcelDtl(mfr, incr);
        modelRequest = parcelDtl.GroupBy(o => o.ResItemId);
    }
    else
    {
        modelRequest = new List<IGrouping<int?, RequestParcelDtl>>();
    }
    
    var dispenseModel = db.Dispenses.Find(intDispenseId);
    var dispenseCode = dispenseModel != null ? dispenseModel.Code : "-";
}

@Html.Hidden("hdDispenseId", intDispenseId)
@Html.Hidden("hdProjectId", intProjectId)

<p class="row-fluid">
    <div>
        @Html.ButtonViewAll()
        <button type="button" onclick="window.location.href ='@Url.Action("DispensReport", new {intDispenseId = intDispenseId })'"
            class="btn button-standard-width btn-small btn-blue" 
            data-rel="tooltip" role="button"  >
            <i class="icon-file bigger-120"></i>&nbsp;&nbsp;รายงานใบรับมอบพัสดุ
        </button>
    </div>
</p>

<hr />

<div class="span11">
    <div class="span5">
        <b>เลขที่การจ่าย : </b><span class="blue">@dispenseCode</span>
    </div> 
</div>

<div class="span11">
    <div class="span5">
        <b>เลขที่ใบเบิก : </b><span class="blue">@ViewBag.ReqCode</span>
    </div>
    <div class="span6">
        <b>วันที่ขอเบิก : </b>@(ViewBag.DispenseDate == null ? "-" : ViewBag.DispenseDate.ToString("dd/MM/yyyy"))
    </div>
</div>

<div class="span11">
    <div class="span5">
        <b>หน่วยงาน : </b>@ViewBag.Jobsite
    </div>
    <div class="span6">
        <b>โครงการ : </b>@ViewBag.ProjectName
    </div>
</div>

<div class="span11">
    <div class="span5">
        <b>เรื่อง : </b>@ViewBag.DispenseName
    </div>
    <div class="span6"></div>
</div>

<div class="span11">
    <div class="span5">
        <b>ผู้ขอ : </b>@ViewBag.FullName
    </div>
    <div class="span6">
        <b>สถานะการขอ : </b>@ViewBag.StatusName                                   
            
    </div>
</div>

<div class="row-fluid">
    <div class="table-header span12">
        <div class="span10">
            @ViewBag.Title
        </div>
        @Html.Partial("_ExportButton")
    </div>
</div>

<table id="tblDetails" class="table table-striped table-bordered table-hover">

    <thead>
        <tr>
            <th style="text-align: center">ประเภทพัสดุ</th>
            <th style="text-align: center">รายการพัสดุ</th>
            <th style="text-align: center; width: 60px">จำนวนที่ขอเบิก</th>
            <th style="text-align: center; width: 60px">จำนวนที่มี</th>
            <th style="text-align: center; width: 60px">จำนวนที่จ่ายแล้ว</th>
            <th></th>
        </tr>
    </thead>

    <tbody>
            
        @foreach (var mg in modelRequest)
        {
            var m = mg.First();
            int sumQuantity = 0;
                
            int whId = m.RequestParcel != null && m.RequestParcel.WarehousePermit !=null ?
                m.RequestParcel.WarehousePermit.WhId : 0;
            var qDispense = (from mh in history
                where mh.RecordStatus != "D" &&
                      mh.DispenseId == intDispenseId &&
                      mh.ResItemId == m.ResItemId
                select mh);
            var dispensed = qDispense.ToList();
             
            if (m.RequestType == "OS")
            {
                var queryA = (from a in db.OfficeSuppliesLots
                    where a.ResItemId == m.ResItemId
                          && a.WhId == whId
                          && a.RecordStatus != "D"
                              select a).OrderBy(x => x.CreatedWhen);

                var ListOffice = queryA.ToList();

                sumQuantity = ListOffice.Sum(x => x.Quantity);
            }
            else
            {
                var queryA = (from a in db.Assets
                    where a.ResItemId == m.ResItemId.Value
                          && a.WhId == whId
                          && a.JobSiteId == null
                          && a.RecordStatus != "D"
                              select a).OrderBy(x => x.CreatedWhen);

                var ListAsset = queryA.ToList();

                sumQuantity = ListAsset.Sum(x => x.Quantity);
            }

            decimal requestQuantity = m.Quantity ?? 0;
             
            var dispensedQuantity = dispensed.Sum(o=>o.Quantity??0);
            //var dispensedQuantityOtherDtl = mg.Sum(o => (decimal) (o.Quantity ?? 0));
            // decimal dispenseQtyDouble = dispensedQuantity - dispensedQuantityOtherDtl;
            <tr>
                <td style="text-align: center">@(Html.Label(m.RequestType == "OS"?"วัสดุ":"ครุภัณฑ์"))</td>
                <td>@Html.DisplayFor(model => m.ItemName)</td>
                <td style="text-align: right">@(requestQuantity.ToString("#,##0.##"))</td>
                
                <td style="text-align: right">@sumQuantity</td>
                <td style="text-align: right">@dispensedQuantity</td>
                <td style="text-align: right;">
                    <div class="hidden-phone visible-desktop btn-group"> 
                        @if (requestQuantity <= dispensedQuantity)
                        {
                            @Html.Label("ทำการจ่ายแล้ว", new { style = "color: Red" })
                        }      
                        else
                        {
                            @Html.Hidden("hdWhId", m.RequestParcel.WarehousePermit.WhId)
                            <a role="button" id="btnDispense" class="btn btn-success btn-mini" 
                               onclick="Dispense(@m.ReqDtlId, @m.ResItemId, @whId, '@m.ItemName',@m.Quantity,'@m.RequestType', '@m.ReqDtlId', '@dispensedQuantity')">
                                ทำการจ่ายพัสดุ
                        @*@requestQuantity == @dispenseQtyDouble , @dispensedQuantityOtherDtl, @mg.Select(o=>o.ItemName + ", " +o.Quantity).FirstOrDefault()*@
                            </a>
                        } 
                    </div>
                </td> 
            </tr>
        }
    </tbody>
</table> 

<div id="mdlList" class="modal hide fade" tabindex="-1" role="dialog" 
    aria-labelledby="myModalLabel" aria-hidden="true" style="display:none">

    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h3 id="headerList">รายการจากคลัง</h3>
    </div>    
    <div class="modal-body">
        <div class="control-group ">
            <div class="control-label">
                ชื่อรายการ :
            </div>
            <div class="controls">
                @Html.TextBox("txtName", "", new { style = "width: 450px;", @readonly = "readonly" })
            </div>
        </div>    
        <div class="control-group">
            <div class="control-label">
                จำนวนทั้งหมด :
            </div>
            <div class="controls">
                @Html.TextBox("txtQtyAll", "", new { style = "width: 100px;", @readonly = "readonly" })
            </div>
        </div> 
        <div class="control-group">
            <div class="control-label">
                จำนวนที่ขอเบิก :
            </div>
            <div class="controls">
                @Html.TextBox("txtQty", "", new { style = "width: 100px;", @readonly = "readonly" })
            </div>
        </div> 
        <div class="control-group">
            <div class="control-label">
                จำนวนที่จ่ายไปแล้ว :
            </div>
            <div class="controls">
                @Html.TextBox("txtQtyDispensed", "", new { style = "width: 100px;", @readonly = "readonly" })
            </div>
        </div>
        <div class="control-group">
            <div class="control-label">
                จำนวนที่จ่าย :
            </div> 
            <div class="controls">
                @Html.TextBox("txtQtyWant", "", new { style = "width: 100px;", @readonly = "readonly" })
            </div>                        
        </div>
        <div id="dvPlace" class="control-group" style="display:none;">
            <div class="control-label">
                รหัสครุภัณฑ์ :
            </div> 
            <div class="controls">
                @Html.TextBox("txtAssetCode", "", new { style = "width: 250px;" })
                <a role="button" id="btnSearchAsset" class="btn btn-success btn-mini" >
                    ค้นหาครุภัณฑ์
                </a>
                <label id="lblMessege" style="color:red"></label> 
            </div>  
                                
        </div>
    <div class="modal-footer">
        <button type="button" id="btnSave">บันทึกข้อมูลการจ่าย</button>
    </div>

</div>
</div>

@section scripts {

    <script type="text/javascript">

        // ค้นหาครุภัณฑ์
        jQuery(function($) {
            $("#btnSearchAsset").click(function() {
                var AssetCode = $("#txtAssetCode").val();
                var WhId = $("#hdWhId").val();
                $.getJSON('@Url.Action("SearchAsset", "Dispense")' + '?strAssetCode=' + AssetCode
                    + '&intWhId=' + WhId, null, function(data) {
                        $("#lblMessege").text(data.message);
                    });
            });
        });

        function Dispense(ReqDtlId, ItemId, WhId, Name, Qty, Type, DtlId, QtyDispensed) {
            $("#mdlList").modal('show');
            $("#txtName").val(Name);
            $("#txtQty").val(Qty);
            $("#txtQtyDispensed").val(QtyDispensed);
            
            if (Type == "A") {
                $("#dvPlace").show();
                $('#txtQtyWant').val("1");
            }
            else {
                $("#dvPlace").hide();
                $('#txtQtyWant').val("0");
                $('#txtQtyWant').removeAttr('readonly');
            }

            $.getJSON('@Url.Action("GetSumQuantity", "Dispense")' + "?intItemId=" + ItemId
                + "&intWhId=" + WhId
                + "&intProjectId=" + $("#hdProjectId").val()
                + "&Type=" + Type + "&intReqDtlId=" + DtlId , null, function (data) {
                    $("#txtQtyAll").val(data.SumQuantity);
            });
                        

            // บันทึกข้อมูลการจ่าย
            jQuery(function($) {
                $("#btnSave").click(function() {
                    AddDispense(ReqDtlId, Type, ItemId, WhId);
                });
            });
        }

        function AddDispense(ReqDtlId, Type, ItemId, WhId) {
            var want = parseInt($("#txtQtyWant").val());
            var qty = parseInt($("#txtQty").val()) - parseInt($("#txtQtyDispensed").val());
                bootbox.confirm("ต้องการบันทึก ใช่หรือไม่?", function (result) {
                    if (result) {
                        if ($("#txtQtyAll").val() <= "0") {
                            alert("ไม่สามารถทำรายการ เนื่องจากจำนวนพัสดุไม่พอ");
                            $("#mdlList").modal('hide');
                        } 
                        if ( want > qty ) {
                            alert("กรอกเกินจำนวนที่สามารถเบิกได้ (คงเหลืออยู่ " + qty + ", ต้องการจ่าย " + want + ")");
                        }
                        else {
                            $.ajax({
                                url: '@Url.Action("CreateDispense", "Dispense")',
                                type: "POST",
                                data: {
                                    intReqDtlId: ReqDtlId,
                                    strType: Type,
                                    intItemId: ItemId,
                                    intWhId: WhId,
                                    intReqQty: parseInt($("#txtQtyWant").val()),
                                    intDispenseId: $("#hdDispenseId").val(),
                                    intProjectId: $("#hdProjectId").val(),
                                    intItemCode: $("#txtAssetCode").val(),
                                    strAssetCode: $("#txtAssetCode").val()
                                    //strPlace: $("#txtPlace").val()
                                },
                                //dataType: "json",
                                success: function (data) {
                                    $("#mdlList").modal('hide');
                                    window.location.href = data.Url;
                                }
                            });
                        }
                    }                   
                });
                return false;
        }
        


        // Validate Qty
        $("#txtQtyWant").bind('keypress', function(e) {
            return (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) ? false : true;
        });

    </script>

}
